﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MLM.AdminCP.Class;
using MLM.Data;

namespace MLM.AdminCP.Pages
{
    public partial class Register : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            RegisterBtn.Click += new EventHandler(RegisterBtn_Click);
            ResetBtn.Click += new EventHandler(ResetBtn_Click);
            MLMDataContext ct = new MLMDataContext();
            PrivacyPolicyLbl.Text = CommonSettingHelper.GetCommonSetting(ct, CommonSettingsContstants.PRIVACY_POLICY);
            if (!IsPostBack)
            {
                if (Request.QueryString["ref"] != null)
                {
                    SponsorIDTxt.Text = Request.QueryString["ref"];
                    SponsorIDTxt.Enabled = false;
                }
            }
        }

        void ResetBtn_Click(object sender, EventArgs e)
        {
            ResetForm();
        }

        void RegisterBtn_Click(object sender, EventArgs e)
        {
            SuccessLtr.Visible = false;
            ErrorLtr.Visible = false;
            try
            {
                MLMDataContext ct = new MLMDataContext();
                var gender = bool.Parse(GenderCombo.SelectedValue);
                var firstName = FirstNameTxt.Text;
                var lastName = LastNameTxt.Text;
                var mobile = MobileTxt.Text;
                var homePhone = HomePhoneTxt.Text;
                var country = long.Parse(CountryDDL.SelectedValue);
                var city = CityTxt.Text;
                var address = AddressTxt.Text;
                var postalCode = PostalCodeTxt.Text;
                var email = EmailTxt.Text;
                var dateOfBirth = DateOfBirthTxt.SelectedDate;
                //bank information
                var bankAccountName = BankAccountNameTxt.Text;
                var bankAccountNumber = BankAccountNumberTxt.Text;
                var bankCode = BankCodeTxt.Text;
                var accountID = AccountIDTxt.Text;
                var bankName = BankNameTxt.Text;
                var swiftCode = SWIFTCodeTxt.Text;
                var bicCode = BICCodeTxt.Text;
                var ibanCode = IBANCodeTxt.Text;
                var isReadPrivacy = PrivacyPolicyChk.Checked;
                //
                var billAddress = BillAddressTxt.Text;
                var billFirstName = BillFirstNameTxt.Text;
                var billLastName = BillLastNameTxt.Text;
                var billpostalCode = BillPostalCodeTxt.Text;
                var billCountryId = long.Parse(BillCountryDDL.SelectedValue);
                var billCity = BillCityTxt.Text;

                var password = Permission.RandomPassword();
                var sponsorid = 0L;
                try
                {
                    sponsorid = long.Parse(SponsorIDTxt.Text);
                }
                catch (Exception)
                {
                }
                var roleid = (int)Permission.PermissionGroup.Distributor;
                if (isReadPrivacy)
                {
                    if (ct.UserInfos.Count(it => it.Email == email) > 0)
                    {
                        ErrorLtr.Text = "Email exits! Please enter another email!";
                        ErrorLtr.Visible = true;
                    }
                    else
                    {
                        var user = new User
                                       {
                                           Password = password,
                                           RoleID = roleid,
                                           RankID = null,
                                           PostalCode = postalCode,
                                           Address = address,
                                           CityName = city,
                                           CountryID = country,
                                           FirstName = firstName,
                                           LastName = lastName,
                                           RegistrationDate = DateTime.Now
                                       };
                        if (sponsorid != 0)
                        {
                            user.SponsorID = sponsorid;
                        }
                        ct.Users.AddObject(user);
                        if (ct.SaveChanges() > 0)
                        {
                            var userId = user.UserId;
                            ct.UserInfos.AddObject(new Data.UserInfo
                                                       {
                                                           CountryID = country,
                                                           DateOfBirth = DateOfBirthTxt.SelectedDate,
                                                           Email = email,
                                                           Gender = gender,
                                                           HomePhone = homePhone,
                                                           Mobile = mobile,
                                                           UserID = userId
                                                       });
                            ct.UserBanks.AddObject(new Data.UserBank
                                                       {
                                                           AccountID = accountID,
                                                           AccountName = bankAccountName,
                                                           AccountNumber = bankAccountNumber,
                                                           BICCode = bicCode,
                                                           BankCode = bankCode,
                                                           BankName = bankName,
                                                           IBANCode = ibanCode,
                                                           SWIFTCode = swiftCode,
                                                           UserID = userId
                                                       });
                            ct.UserPaymentInfos.AddObject(new UserPaymentInfo
                                                              {
                                                                  Address = billAddress,
                                                                  UserID = userId,
                                                                  LastName = billLastName,
                                                                  FirstName = billFirstName,
                                                                  CountryID = billCountryId,
                                                                  CityName = billCity,
                                                                  PostalCode = billpostalCode
                                                              });
                            if (ct.SaveChanges() > 0)
                            {
                                try
                                {
                                    Email.Send_Email(email, "Login Information",
                                                     CommonSettingHelper.GetCommonSetting(ct,
                                                                                          CommonSettingsContstants.
                                                                                              REGISTERCOMPLETED).Replace
                                                         ("{{PASSWORD}}", password).Replace("{{USERID}}",
                                                                                            userId.ToString()));
                                    ResetForm();
                                    SuccessLtr.Text = "Register successfuly! Please check email!";
                                    SuccessLtr.Visible = true;
                                    ErrorLtr.Visible = false;
                                }
                                catch (Exception)
                                {
                                    ErrorLtr.Text = "Error! Please check your input form!";
                                    ErrorLtr.Visible = true;
                                }
                            }
                            else
                            {
                                ErrorLtr.Text = "Error! Please check your input form!";
                                ErrorLtr.Visible = true;
                            }
                        }
                    }
                }
                else
                {
                    ErrorLtr.Text = "You must agree with the Privacy Policy to continued!";
                    ErrorLtr.Visible = true;
                }
            }
            catch (Exception)
            {
                ErrorLtr.Text = "Error! Please check your input form!";
                ErrorLtr.Visible = true;
            }
        }
        public void ResetForm()
        {
            GenderCombo.SelectedValue = "1";
            FirstNameTxt.Text = "";
            LastNameTxt.Text = "";
            MobileTxt.Text = "";
            HomePhoneTxt.Text = "";
            AddressTxt.Text = "";
            PostalCodeTxt.Text = "";
            EmailTxt.Text = "";
            BankAccountNameTxt.Text = "";
            BankAccountNumberTxt.Text = "";
            BankCodeTxt.Text = "";
            BankNameTxt.Text = "";
            SWIFTCodeTxt.Text = "";
            AccountIDTxt.Text = "";
            BICCodeTxt.Text = "";
            IBANCodeTxt.Text = "";
            PrivacyPolicyChk.Checked = false;
            ErrorLtr.Visible = false;
            SuccessLtr.Visible = false;
        }
    }
}